package org.altervista.cp.thinjdbc.wrappers;

import java.sql.SQLException;
import java.util.Arrays;

import org.altervista.cp.thinbcgen.proxy.ExceptionHandler;
import org.altervista.cp.thinbcgen.proxy.Proxy;

public class SQLRuntimeException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public static final ExceptionHandler EH = new ExceptionHandler() {
		public Object handle(Proxy proxy, Throwable t, String methodName,
				Object[] params) {
			StringBuffer paramSB = new StringBuffer();
			if (params != null) {
				paramSB.append(Arrays.toString(params));
				paramSB.deleteCharAt(0);
				paramSB.deleteCharAt(paramSB.length() - 1);
			}
			throw new SQLRuntimeException("Method " + methodName + "("
					+ paramSB + ") threw an exception", (SQLException) t);
		}
	};

	public SQLRuntimeException(String message) {
		super(formatMessage(message));
	}

	public SQLRuntimeException(SQLException cause) {
		super(cause);
	}

	public SQLRuntimeException(String message, SQLException cause) {
		super(formatMessage(message), cause);
	}

	public SQLException getSQLCause() {
		return (SQLException) getCause();
	}

	private static final String formatMessage(String message) {
		return "[" + Thread.currentThread().getName() + "] - " + message;
	}

}
